#import <SystemConfiguration/SystemConfiguration.h>
#import "IDominoAppDelegate.h"
#import "Constants.h"
#import "PersonalContactXMLReader.h"
#import "DirectoryContactXMLReader.h"
#import "CalendarXMLReader.h"
#import "MailListXMLReader.h"
#import "PersonInfoHTMLReader.h"
#import "ContactSelectionViewController.h"
#import "URLLoadingOperation.h"
#import "FileDownloader.h"

@implementation IDominoAppDelegate

@synthesize window, tabBarController, contactNavigationController, contactListViewController, contactContentController,
calendarNavigationController, calendarListViewController, calendarContentController, contactContentWebViewController, 
authenticationController, transactionViewController,
segmentedControl, mailNavigationController, mailContentController, mailEditController,
mailListViewController, mailBoxViewController, mailBoxDict, databaseInteraction, currentMailBox,requestQueue,
localMailDict, mailWebViewController, mailWebView, _loginUsername, _loginPassword, _mailServer, _databaseName, _sessionCookie, _serverName,
_serverLoginURL, _serverGetCookieURL,calendarWebView, contactContentWebView;

#pragma mark AppDelegate Logic

- init {
	if (self = [super init]) {
		databaseInteraction=[[DatabaseInteraction alloc] init];//Utitlity for database operation
		requestQueue = [[NSOperationQueue alloc] init];//Key Operation Queue
		[requestQueue setMaxConcurrentOperationCount:4];
		theLock = [[NSLock alloc] init];//Lock for sending HTTP request
	}
	return self;
}


- (void)applicationDidFinishLaunching:(UIApplication *)application {

	currentMailBox=NSLocalizedString(@"Inbox", @"Inbox title");//default is loading inbox content
	_isOffline=NO;//Offline Switch
	_sessionCookie=[[NSMutableString alloc] init];//cookie for login
	mailBoxDict = [[NSMutableDictionary alloc] init];
	localMailDict=[[NSMutableDictionary alloc] init];
	
	//init all View Controller;
	authenticationController=[[AuthenticationController alloc] init];
	
	calendarListViewController = [[CalendarListViewController alloc] initWithStyle:UITableViewStylePlain];
	calendarContentController=[[ UIViewController alloc] init];
	calendarContentController.hidesBottomBarWhenPushed=YES;
	self.calendarNavigationController = [[UINavigationController alloc] initWithRootViewController:calendarListViewController];
	
	contactListViewController = [[ContactListViewController alloc] init];
	contactContentController = [[ContactContentViewController alloc] initWithStyle:UITableViewStylePlain];
	contactContentWebViewController=[[ UIViewController alloc] init];
	contactContentWebViewController.hidesBottomBarWhenPushed=YES;
	self.contactNavigationController = [[UINavigationController alloc] initWithRootViewController:contactListViewController];
	
	mailBoxViewController = [[MailViewController alloc] initWithStyle:UITableViewStylePlain];
	mailListViewController=[[ MailListViewController alloc] init];
	mailContentController=[[ MailContentViewController alloc] init];
	mailWebViewController=[[ UIViewController alloc] init];
	mailEditController = [[MailEditViewController alloc] init];
	self.mailNavigationController = [[UINavigationController alloc] initWithRootViewController:mailBoxViewController];
	currentNavigationController=mailNavigationController;
	
	transactionViewController=[[TransactionViewController alloc] initWithStyle:UITableViewStylePlain];
	UINavigationController* transactionNavigationController=[[UINavigationController alloc] initWithRootViewController:transactionViewController];
	
	//add all View Controller to TabController
	NSArray* array=[NSArray arrayWithObjects:self.mailNavigationController, self.calendarNavigationController, self.contactNavigationController, transactionNavigationController, nil];
	[tabBarController setViewControllers:array animated:YES];
	[window addSubview:tabBarController.view];
	
	[self loadPreference];//load application preference

	[self initUI];		//init UI
	[self getMailList];
	//default login action
	
	[NSThread detachNewThreadSelector:@selector(login) toTarget:self withObject:nil];
	[window setNeedsDisplay];
	[transactionNavigationController release];
    [mailListViewController setMailStatusBarWithMessage:NSLocalizedString(@"Login", @"Login Server:") animateIndicator:YES];

}

- (void)dealloc {
	[requestQueue release];
	[databaseInteraction release];
	[_sessionCookie release];
	[mailBoxDict release];
	[localMailDict release];
	[theLock release];
	[calendarListViewController release];
	[calendarWebView release];
	[authenticationController release];
	[calendarContentController release];
	[contactContentWebViewController release];
	[contactListViewController release];
	[contactContentController release];
	[contactContentWebView release];
	[contactNavigationController release];
	[mailEditController release];
	[mailBoxViewController release];
	[mailListViewController release];
	[mailContentController release];
	[mailWebViewController release];
	[mailNavigationController release];
	[mailWebView release];
	[TransactionViewController release];
	
    [window release];
    [super dealloc];
}


#pragma mark login function
- (void) login
{ 		
	if(!_useWebSeal){
		[self loginDirect];
		return;
	}
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	_isOffline=YES;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	//the post data
	NSData* loginData = [ [NSString stringWithFormat:@"username=%@&password=%@&login-form-type=pwd",_loginUsername,_loginPassword]
						 dataUsingEncoding: NSUTF8StringEncoding];
	
    // Create a new HTTP request.
    CFHTTPMessageRef loginRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("POST"), (CFURLRef)_serverLoginURL, kCFHTTPVersion1_1);
	CFHTTPMessageSetBody(loginRequest, (CFDataRef)loginData);
	CFReadStreamRef responseStream= CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, loginRequest);
	CFReadStreamSetProperty(responseStream, kCFStreamPropertyHTTPAttemptPersistentConnection,  kCFBooleanTrue);
	CFReadStreamSetProperty(responseStream, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue);
	
	if (!CFReadStreamOpen(responseStream)) {
		CFRelease(responseStream);
		responseStream = NULL;
		NSLog(@"Login Action: Can't Open Response Stream.");
		CFRelease(loginRequest);
		return;
	}
	
    CFRelease(loginRequest);
	
    if (!responseStream) {
        NSLog( @"Login Action: Creating the stream failed.");
		return;
    }
	
	//enter a loop to wait the response data
	BOOL done=FALSE;
	CFHTTPMessageRef msgResponse;
	while (!done) {
		if(CFReadStreamHasBytesAvailable(responseStream)){
			UInt8 buffer[4096];
			CFIndex bytesRead = CFReadStreamRead(responseStream, buffer, sizeof(buffer));
			// Less than zero is an error
			if (bytesRead <= 0){
				NSLog(@"Login Action: No Incoming Stream Error.");
				CFRelease(responseStream);
				return;
			}	
			else {
				msgResponse = (CFHTTPMessageRef) CFReadStreamCopyProperty(responseStream, kCFStreamPropertyHTTPResponseHeader);
				NSData* theRequest = (NSData *) CFHTTPMessageCopySerializedMessage(msgResponse);
				NSString* dataResponse = [[NSString alloc] initWithData:theRequest encoding:NSUTF8StringEncoding];
				NSString * cookiePos = @"Set-Cookie:";	
				NSRange range = [dataResponse rangeOfString:cookiePos];
				
				//if the username and password is invalid, create a new View to get the user information
				if(range.length==0){
					
					UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
																								target:self action:@selector(authenInfoAction:)];
					authenticationController.navigationItem.rightBarButtonItem = doneButton;
					[doneButton release];
					[mailNavigationController pushViewController:authenticationController animated:YES];
					CFReadStreamClose(responseStream);
					CFRelease(responseStream);
					[dataResponse release];
					[theRequest release];
					CFRelease(msgResponse);
					return;
				}
				
				NSMutableString* tempcookie=[[NSMutableString alloc] init];
				if (range.length != 0) {
					[tempcookie setString:[dataResponse substringFromIndex: (range.location+12)]];
				}
				range=[tempcookie rangeOfString:@";"];
				[_sessionCookie appendString:[tempcookie substringToIndex:range.location+1]];
				NSRange range1=[tempcookie rangeOfString:@"PD-ECC="]; 
				NSString* temp=[tempcookie substringFromIndex:range1.location] ;
				range=[temp rangeOfString:@";"];
				[_sessionCookie appendString:[temp substringToIndex:range.location]];
				done = TRUE;	
				[theRequest release];
				[tempcookie release];
				[dataResponse release];
			}
		}
		else{
			if(CFReadStreamGetStatus(responseStream)==kCFStreamStatusError){
				[self.mailListViewController setMailStatusBarWithMessage:NSLocalizedString(@"Local", @"Local data") animateIndicator:NO];
				UIBarButtonItem *localItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Offline", @"Offline") style:UIBarButtonItemStylePlain target:self action:@selector(localAction:)];
				self.mailBoxViewController.navigationItem.leftBarButtonItem=localItem;
				CFReadStreamClose(responseStream);
				CFRelease(responseStream);
				[localItem release];
				return;
			}
		}
	}
	CFReadStreamClose(responseStream);
	CFRelease(responseStream);
	CFRelease(msgResponse);
	
	//The Second step is to get the PD-ID number by PD-SESSION-ID and PD-ECC
	
	CFHTTPMessageRef requestMsg = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), (CFURLRef)_serverGetCookieURL, kCFHTTPVersion1_1);
	CFHTTPMessageSetHeaderFieldValue(requestMsg, CFSTR("Cookie"), (CFStringRef)_sessionCookie);
	responseStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, requestMsg);
	CFReadStreamSetProperty(responseStream, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue);
	CFReadStreamSetProperty(responseStream, kCFStreamPropertyHTTPAttemptPersistentConnection,  kCFBooleanTrue);
	CFRelease(requestMsg);
	if (!responseStream) {
		CFRelease(responseStream);
		responseStream=NULL;
		NSLog(@"Login Action: Can't Open Response Stream.");
		return;
	}
	
	if (!CFReadStreamOpen(responseStream)) {
		CFRelease(responseStream);
		responseStream = NULL;
		NSLog( @"Login Action: Creating the stream failed.");
		return ;
	}
	done = FALSE;
	while (!done) {
		if (CFReadStreamHasBytesAvailable(responseStream)) {
			//UInt8 buffer[4096];
			//CFIndex bytesRead = CFReadStreamRead(responseStream, buffer, sizeof(buffer));
			CFHTTPMessageRef msgResponse = (CFHTTPMessageRef) CFReadStreamCopyProperty(responseStream, kCFStreamPropertyHTTPResponseHeader);
			NSData* theRequest = (NSData *) CFHTTPMessageCopySerializedMessage(msgResponse);
			NSString* dataResponse = [[NSString alloc] initWithData:theRequest encoding:NSUTF8StringEncoding];
			
			//set the cookie value, then we can access the domino server
			NSString * cookiePos = @"Set-Cookie:";
			NSRange range = [dataResponse rangeOfString:cookiePos];
			NSMutableString* tempcookie=[[NSMutableString alloc] init] ;
			if (range.length != 0) {
				[tempcookie setString:[dataResponse substringFromIndex: (range.location+12)]];
			}
			range=[tempcookie rangeOfString:@";"];
			NSRange range2=[_sessionCookie rangeOfString:@";"];
			range2.length=range2.location+1;
			range2.location=0;
			[_sessionCookie replaceCharactersInRange:range2 withString:[tempcookie substringToIndex:range.location+2]];
			NSRange range1=[tempcookie rangeOfString:@"PD-ID="]; 
			NSString* temp=[tempcookie substringFromIndex:range1.location] ;
			range=[temp rangeOfString:@";"];
			[_sessionCookie appendString:@"; "];
			[_sessionCookie appendString:[temp substringToIndex:range.location]];
			done=true;
			[tempcookie release];
			[theRequest release];
			[dataResponse release];
			CFRelease(msgResponse);
		}
	}
	CFReadStreamClose(responseStream);
	CFRelease(responseStream);
	responseStream = NULL;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	_isOffline=NO;
		//Go to the default behaviour after login
	
	[mailListViewController setMailStatusBarWithMessage:NSLocalizedString(@"FinishLogin", @"Finish Login, Updating mail...") animateIndicator:YES];
	[transactionViewController addToHistroyTransaction:NSLocalizedString(@"LoginSuccessful", @"Login Successfuly")];
	[mailBoxDict removeAllObjects];
	[NSThread detachNewThreadSelector:@selector(getMailList) toTarget:self withObject:nil];
	[self getSavedTransaction];
	[pool release];
	return ;
}

- (void) loginDirect
{ 		
	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	_isOffline=YES;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	//the post data
	NSData* loginData = [ [NSString stringWithFormat:@"username=%@&password=%@",_loginUsername,_loginPassword]
						 dataUsingEncoding: NSUTF8StringEncoding];
	
    // Create a new HTTP request.//
	NSString* loginURL=[NSString stringWithFormat:@"%@/names.nsf?Login",_serverName];
    CFHTTPMessageRef loginRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("POST"), (CFURLRef)[NSURL URLWithString:loginURL], kCFHTTPVersion1_1);
	CFHTTPMessageSetBody(loginRequest, (CFDataRef)loginData);
	CFReadStreamRef responseStream= CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, loginRequest);
	
	if (!CFReadStreamOpen(responseStream)) {
		CFRelease(responseStream);
		responseStream = NULL;
		CFRelease(loginRequest);
		NSLog(@"Login Action: Can't Open Response Stream.");
		return;
	}
	
    CFRelease(loginRequest);
	
    if (!responseStream) {
        NSLog( @"Login Action: Creating the stream failed.");
		return;
    }

	//enter a loop to wait the response data
	BOOL done=FALSE;
	while (!done) {
		if(CFReadStreamHasBytesAvailable(responseStream)){
			CFHTTPMessageRef msgResponse1 = (CFHTTPMessageRef) CFReadStreamCopyProperty(responseStream, kCFStreamPropertyHTTPResponseHeader);
			NSData* theRequest1 = (NSData *) CFHTTPMessageCopySerializedMessage(msgResponse1);
			NSString* dataResponse1 = [[NSString alloc] initWithData:theRequest1 encoding:NSUTF8StringEncoding];
			NSString * cookiePos = @"Set-Cookie:";
			NSRange range = [dataResponse1 rangeOfString:cookiePos];
			NSString* cookie=dataResponse1;

			if (range.length != 0) {
				cookie=[cookie substringFromIndex: (range.location+12)];
			}

			range=[cookie rangeOfString:@";"];
			[_sessionCookie appendString:[cookie substringToIndex:range.location]];
			[dataResponse1 release];
			CFRelease(msgResponse1);
			[theRequest1 release];
			done=YES;
			
		}
	}
	
	CFReadStreamClose(responseStream);
	CFRelease(responseStream);
	
	responseStream = NULL;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	//Go to the default behaviour after login
	_isOffline=NO;
	[mailListViewController setMailStatusBarWithMessage:NSLocalizedString(@"FinishLogin", @"Finish Login, Updating mail...") animateIndicator:YES];
	[mailBoxDict removeAllObjects];
	[NSThread detachNewThreadSelector:@selector(getMailList) toTarget:self withObject:nil];
	[self getSavedTransaction];
	[pool release];
	return ;
}

#pragma mark mail function
- (void)getMailList
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSString* mailBox=currentMailBox;
	if([mailBoxDict objectForKey:mailBox]==nil){	

		if ([self isDataSourceAvailable] ) {

			NSURL *fetchMailUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/%@/($%@)?ReadViewEntries&count=%d&ResortDescending=4", _serverName, _mailServer,  _databaseName, mailBox, _defaultMaxMail]];
			NSString* responseString=[self sendHttpRequest:fetchMailUrl isPost:NO postData:nil];	
			NSData* urlData=[responseString dataUsingEncoding: NSUTF8StringEncoding];
			MailListXMLReader *streamingParser = [[MailListXMLReader alloc] init];
			NSError *parseError = nil;
			NSArray* mailEntryArray=[streamingParser parseXMLFileFromData:urlData parseError:&parseError];

			int mailCount=streamingParser.mailCount;
			[streamingParser release]; 
			NSString* updateTime=[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"Updated", @""),
								  [[[NSDate date] description] substringToIndex:16]];
			[mailListViewController setMailStatusBarWithMessage:updateTime animateIndicator:NO];
			
			[mailBoxDict setObject:updateTime forKey:[NSString stringWithFormat:@"%@updateTime", mailBox]];
			[mailBoxDict setObject:[NSString stringWithFormat:@"%d",mailCount] forKey:[NSString stringWithFormat:@"%@mailCount", mailBox]];
			
			[mailListViewController setDisplayList:mailEntryArray];
			[transactionViewController addToHistroyTransaction:[NSString stringWithFormat:@"%@%@", NSLocalizedString(mailBox,@""),
																NSLocalizedString(@"MailListUpdated", @"Updated")]];
			[self  performSelectorInBackground:@selector(getAllMailContent:) withObject:mailBox];
		}else{
			[self loadLocalMails:mailBox];
		}
		[mailBoxDict setObject:mailListViewController.currentMailList  forKey:mailBox];
	}
	else{
		[mailListViewController setDisplayList:[mailBoxDict objectForKey:mailBox]];
		[mailListViewController setMailStatusBarWithMessage:[mailBoxDict objectForKey:[NSString stringWithFormat:@"%@updateTime",mailBox]] animateIndicator:NO];
	}
	[pool release];
}

- (void)getAllMailContent:(NSString*)mailBox{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSArray* array=[[mailBoxDict objectForKey:mailBox] copy];
	URLLoadingOperation* newOperation=[[URLLoadingOperation alloc] initWithMailArray:array mailBox:mailBox];
	[newOperation setQueuePriority:NSOperationQueuePriorityVeryLow];
	[requestQueue addOperation:newOperation];
	[array release];
	[newOperation release];
	[pool release];
}

- (void)showMailInfo:(Mail *)mailInfo
{	
	int sequence;
	sequence=[mailListViewController.currentMailList indexOfObject:mailInfo]+1;
	if([mailListViewController.currentMailList count]==0) {
		sequence=0;
		[segmentedControl setEnabled:NO forSegmentAtIndex:0];
	}
	else if(sequence==NSNotFound)
		return;
	if(sequence==[mailListViewController.currentMailList count])
		[segmentedControl setEnabled:NO forSegmentAtIndex:1];
	else if(sequence==1)
		[segmentedControl setEnabled:NO forSegmentAtIndex:0];
	else{
		[segmentedControl setEnabled:YES forSegmentAtIndex:0];	
		[segmentedControl setEnabled:YES forSegmentAtIndex:1];	
	}
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	mailContentController.navigationItem.title = [NSString stringWithFormat:@"%d/%d", sequence, [mailListViewController.currentMailList count]];

	if(![mailInfo hasContentDownloaded] && [self isDataSourceAvailable]){
		NSURL* fetchMailContentUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/%@/($%@)/%@/?OpenDocument&Form=m_MailReplyEdit&PresetFields=ParentUNID;%@", _serverName, _mailServer,_databaseName, currentMailBox, [mailInfo UNID], [mailInfo UNID]]];
		NSString* all=[self sendHttpRequest:fetchMailContentUrl isPost:NO postData:nil];
		NSRange range=[all rangeOfString:@"<textarea class=\"memoComposeField memoFieldText\" id=\"msgBody\" name=\"Body\">"];
		if(range.location!=NSNotFound){
			all=[all substringFromIndex:range.location+77];
			all=[all substringToIndex:[all rangeOfString:@"</textarea>"].location];
			NSString* toString=[all substringFromIndex:[all rangeOfString:@"To:"].location+3];
			toString=[toString substringToIndex:[toString rangeOfString:@"\n"].location];
			NSString* fromString=[all substringFromIndex:[all rangeOfString:@"From:"].location+5];
			fromString=[fromString substringToIndex:[fromString rangeOfString:@"\n"].location];
			NSString* content=[all substringFromIndex:[all rangeOfString:@"=======================" options:NSBackwardsSearch].location+24 ]; 
			while([content hasPrefix:@"\n"])
				content=[content substringFromIndex:1];
			NSMutableString* content1=[NSMutableString stringWithString:content];
			[content1 replaceOccurrencesOfString:@"&quot;" withString:@"\"" options:NSBackwardsSearch range:NSMakeRange(0,content1.length)];
			[content1 replaceOccurrencesOfString:@"&amp;" withString:@"&" options:NSBackwardsSearch range:NSMakeRange(0,content1.length)];
			[content1 replaceOccurrencesOfString:@"&lt;" withString:@"<" options:NSBackwardsSearch range:NSMakeRange(0,content1.length)];
			[content1 replaceOccurrencesOfString:@"&gt;" withString:@">" options:NSBackwardsSearch range:NSMakeRange(0,content1.length)];
			if([mailInfo hasAttachment]){
				range=[content1 rangeOfString:@"[attachment(s) \""];
				if(range.location!=NSNotFound){
					NSString* attachmentName=[content1 substringFromIndex:range.location+range.length];
					attachmentName=[attachmentName substringToIndex:[attachmentName rangeOfString:@"\""].location];	
					[mailInfo setAttachmentName:attachmentName];
					int size=([[mailInfo size] intValue]/1024);
					content1=[NSString stringWithFormat:@"%@Attachment:%@ %dKB", [content1 substringToIndex:range.location], attachmentName,size];
				}
			}
			[mailInfo setFullSender:fromString];
			[mailInfo setReceiver:toString];
			[mailInfo setContent:content1];
			[mailInfo markDownload];
		}
	}
	[mailContentController setReceiver:[mailInfo receiver] fullSender:[mailInfo fullSender] subject:[mailInfo subject] date:[mailInfo date] content:[mailInfo content]];
	if([[self mailNavigationController] topViewController]!=mailContentController)
		[[self mailNavigationController] pushViewController:mailContentController animated:YES];
	currentMail=mailInfo;
	if([mailInfo hasRead]==NO){
		[mailInfo markRead];
		[self setMailReadStatusWithUNID:[mailInfo UNID] markRead:YES]; 
	}
	[pool release];
}




#pragma mark Calendar
- (void)getCalendarList
{
	if(![self isDataSourceAvailable]){
		[self showNotLoginAlert];
		return;
	}
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSDateFormatter* transfer=[[NSDateFormatter alloc] init];
	[transfer setDateFormat:@"yyyyMMdd"];
	NSString* endDate=[transfer stringFromDate: [NSDate dateWithTimeIntervalSinceNow:60*60*24*calendarListViewController.calendarEndDate]];
    NSString* beginDate=[transfer stringFromDate: [NSDate dateWithTimeIntervalSinceNow:60*60*24*calendarListViewController.calendarStartDate]];
	[transfer release];
	NSURL *fetchCalendarUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/%@/($Calendar)?ReadViewEntries&startKey=%@T000000&untilKey=%@T000000&keyType=time", _serverName, _mailServer,  _databaseName, beginDate, endDate]];
	NSString* responseString=[self sendHttpRequest:fetchCalendarUrl isPost:NO  postData:nil];
	NSData* urlData=[responseString dataUsingEncoding:NSUTF8StringEncoding];
    CalendarXMLReader *streamingParser = [[CalendarXMLReader alloc] init];
	NSError *parseError = nil;
    NSArray* calendarEntryArray=[streamingParser parseXMLFileFromData:urlData parseError:&parseError];
    [streamingParser release];   
	[calendarListViewController setUpDisplayList:calendarEntryArray];
	[transactionViewController addToHistroyTransaction:NSLocalizedString(@"CalendarListUpdated", @"Calendar List Updated")];
	[pool release];
}

- (void)showCalendarInfo:(Calendar *)calendarInfo
{
	if(![self isDataSourceAvailable]){
		[self showNotLoginAlert];
		return;
	}
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	calendarContentController.navigationItem.title = [calendarInfo subject];
	if([calendarNavigationController topViewController] != calendarContentController)
		[calendarNavigationController pushViewController:calendarContentController animated:YES];
	NSString* contentURL=[NSString stringWithFormat:@"%@/%@/%@/($Calendar)/%@/?OpenDocument&ui=webmail",_serverName, _mailServer,_databaseName, 	[calendarInfo UNID]];
	NSURL* fetchCalendarContentUrl = [NSURL URLWithString:contentURL];
	NSMutableString *content=[[NSMutableString alloc] init];
	[content appendString:[self sendHttpRequest:fetchCalendarContentUrl  isPost:NO  postData:nil]];
	[content replaceOccurrencesOfString:@"<font size=\"2\">" withString:@"<font size=\"8\">" options:NSCaseInsensitiveSearch  range:NSMakeRange(0,[content length])];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;	
	[calendarWebView loadHTMLString:	content baseURL:nil];
	[content release];
	[pool release];
}


#pragma mark contact

- (void)showPersonInfo:(Person *)personInfo
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	if([personInfo updatedInDatabase]==NO){
		if(![self isDataSourceAvailable])
			return ;
		else
			[self getPersonInfoByPerson:personInfo];
	}
	contactContentController.navigationItem.title = [personInfo firstName];
	if([contactNavigationController topViewController] != contactContentController)
		[[self contactNavigationController] pushViewController:contactContentController animated:YES];
	[contactContentController setUpDisplayList:personInfo];
	[pool release];
}

- (void)showDirectoryPersonInfo:(Person *)personInfo
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	if([personInfo updatedInDatabase]==NO){
		if(![self isDataSourceAvailable])
			return ;
		else
			[self getDirectoryInfoByPerson:personInfo];
	}	
	contactContentController.navigationItem.title = [personInfo firstName];
	if([contactNavigationController topViewController] != contactContentController)
		[[self contactNavigationController] pushViewController:contactContentController animated:YES];
	[contactContentController setUpDisplayList:personInfo];
	[pool release];	
}


- (void)updateContacts:(BOOL)isPersonal
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	URLLoadingOperation* newOperation;
	if(isPersonal==YES){
		newOperation=[[URLLoadingOperation alloc] initWithType:4];
		[newOperation setQueuePriority:NSOperationQueuePriorityNormal];
		[requestQueue addOperation:newOperation];
		[newOperation release];
	}
	else{
		newOperation=[[URLLoadingOperation alloc] initWithType:5];
		[newOperation setQueuePriority:NSOperationQueuePriorityNormal];
		[requestQueue addOperation:newOperation];
		[newOperation release];
	}
	
	[pool release];
}


#pragma mark tabBarAction
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
	if(viewController==mailNavigationController){
		if([mailListViewController.currentMailList count]!=0)
			[NSThread detachNewThreadSelector:@selector(getMailList) toTarget:self withObject:nil];
		currentNavigationController=mailNavigationController;//can be improve *************?		
	}
	else if(viewController==calendarNavigationController){
		if([calendarListViewController isCalendarEmpty])
			[NSThread detachNewThreadSelector:@selector(getCalendarList) toTarget:self withObject:nil];
		currentNavigationController=calendarNavigationController;		
	}
	else if(viewController==contactNavigationController){
		[self.contactListViewController initDisplayList];
		currentNavigationController=contactNavigationController;
	}
	else
		currentNavigationController=nil;
}


#pragma mark allAction
- (void)authenInfoAction:(id)sender
{
	if(![authenticationController setParameters])
		return;
	[mailNavigationController popViewControllerAnimated:YES];
	[NSThread detachNewThreadSelector:@selector(login) toTarget:self withObject:nil];
	[authenticationController release];
}

- (void)segmentAction:(id)sender 
{
	UISegmentedControl* segCtl = sender;
	//get the index in the table
	NSIndexPath* index;
	UITableView* tableView;
	
	if(currentNavigationController==mailNavigationController){
		tableView=mailListViewController._tableView;
		index=[mailListViewController currentIndexPath];
	}
	else if(currentNavigationController==calendarNavigationController){
		tableView=[calendarListViewController tableView];
		index=[calendarListViewController currentIndexPath];
	} else {
		return;
	}
	NSIndexPath* newIndex;
	if([segCtl selectedSegmentIndex]==0){
		if(index.row==0){
			newIndex=[NSIndexPath indexPathWithIndex:index.section-1];
			newIndex=[newIndex indexPathByAddingIndex:[tableView numberOfRowsInSection:index.section-1]-1];
		}
		else{	
			newIndex=[NSIndexPath indexPathWithIndex:index.section];
			newIndex=[newIndex indexPathByAddingIndex: index.row-1];
		}
	}
	else{
		if([tableView numberOfRowsInSection:index.section]>(index.row+1)){
			newIndex=[NSIndexPath indexPathWithIndex:index.section];
			newIndex=[newIndex indexPathByAddingIndex: index.row+1];
			
		}
		else{
			newIndex=[NSIndexPath indexPathWithIndex:index.section+1];
			newIndex=[newIndex indexPathByAddingIndex: 0];
		}
	}
	if(currentNavigationController==mailNavigationController){
		[mailListViewController tableView:tableView didSelectRowAtIndexPath:newIndex];
	}
	else if(currentNavigationController==calendarNavigationController){
		[calendarListViewController tableView:tableView didSelectRowAtIndexPath:newIndex];
	}

	[tableView  selectRowAtIndexPath:newIndex animated:YES scrollPosition:  UITableViewScrollPositionNone];
}


- (void)webViewAction:(id)sender 
{
	
	[mailNavigationController pushViewController:mailWebViewController animated:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if([currentMail hasAttachment]){
		NSFileManager *fileManager = [NSFileManager defaultManager];
		NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDirectory = [paths objectAtIndex:0];
		NSString* name=[NSString stringWithFormat:@"%@%@",[currentMail UNID],[currentMail attachmentName]];
		NSString* path =[[documentsDirectory stringByAppendingPathComponent:@"Attachments"] stringByAppendingPathComponent:name];
		NSString* fetchURL=[NSString stringWithFormat:@"%@/%@/%@/0/%@/$File/%@?OpenElement",_serverName,_mailServer,_databaseName, [currentMail UNID],[currentMail attachmentName]];
		if([fileManager fileExistsAtPath:path]){
			NSURL* url=[NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
			NSURLRequest* request=[[NSURLRequest alloc] initWithURL:url];
			[mailWebView loadRequest:request];
			[request release];
		}else{
			if(![self isDataSourceAvailable]){
				[self showNotLoginAlert];
				return;
			}
			FileDownloader* filedownloader=[[FileDownloader alloc] initWithString:fetchURL
																		 filename:path cookie:_sessionCookie];
			[filedownloader startDownloadingURL];	
			[filedownloader release];
		}
		mailWebViewController.navigationItem.title=[currentMail attachmentName];
	}
	else{
		if(![self isDataSourceAvailable]){
			[self showNotLoginAlert];
			return;
		}
		NSString* fetchURL=[NSString stringWithFormat:@"%@/%@/%@/($%@)/%@/?OpenDocument&Form=m_DocumentRead&Details",_serverName,_mailServer,_databaseName, currentMailBox, 	[currentMail UNID]];
		NSMutableURLRequest* request=[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:fetchURL]];
		[request addValue:_sessionCookie forHTTPHeaderField:@"Cookie"];
		[mailWebView loadRequest:request];
		[request release];
		mailWebViewController.navigationItem.title=[currentMail subject];
	}
}

- (void)openInSafariAction:(id)sender
{
	NSString* fetchURL=[NSString stringWithFormat:@"%@/%@/%@/($%@)/%@/?OpenDocument&Form=m_DocumentRead&Details",_serverName, _mailServer,_databaseName, currentMailBox, 	[currentMail UNID]];
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:fetchURL]];
}

- (void)openInINotesAction:(id)sender
{
	if(![self isDataSourceAvailable]){
		[self showNotLoginAlert];
		return;
	}
	NSString* contentURL=[NSString stringWithFormat:@"%@/%@/%@/(iNotes_Contacts)/%@/?OpenDocument&Form=m_DocumentRead",_serverName, _mailServer,_databaseName, 	[[contactContentController currentPerson] UNID]];
	NSURL* fetchContactContentUrl = [NSURL URLWithString:contentURL];
	NSMutableURLRequest* request=[[NSMutableURLRequest alloc] initWithURL:fetchContactContentUrl];
	[request addValue:_sessionCookie forHTTPHeaderField:@"Cookie"];
	[contactContentWebView loadRequest:request];
	[request release];
	[contactNavigationController pushViewController:contactContentWebViewController animated:YES];
}

- (void)composeAction:(id)sender
{
	[mailNavigationController pushViewController:mailEditController  animated:YES ];//presentModalViewController: mailEditController animated:YES];
	[mailEditController.toTextField becomeFirstResponder];
}

- (void)replyAction:(id)sender
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	if([self isDataSourceAvailable]){
		NSString* url=	[NSString stringWithFormat:@"%@/%@/%@/($Drafts)/$new/?EditDocument&Form=m_MailReplyEdit&PresetFields=ParentUNID;%@",_serverName, _mailServer,_databaseName,[currentMail UNID]];
		NSURL* fetchReplyURL = [NSURL URLWithString:url];
		NSString* all=[self sendHttpRequest:fetchReplyURL isPost:NO postData:nil];
		NSRange range=[all rangeOfString:@"<textarea class=\"memoComposeField memoFieldText\" id=\"msgBody\" name=\"Body\">"];
		if(range.location!=NSNotFound){
			all=[all substringFromIndex:range.location+77];
			NSMutableString* modify=[[NSMutableString alloc] initWithString:[all substringToIndex:[all rangeOfString:@"</textarea>"].location]];
			[modify replaceOccurrencesOfString:@"=" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [modify length])];
			[mailEditController.textView setText:modify];
			[modify release];
		}
	}else{
		[mailEditController.textView setText:[currentMail content]];
	}
	[mailEditController.toTextField setText:[currentMail fullSender]];
	[mailEditController.subjectTextField setText:[NSString stringWithFormat:@"Re:%@", [currentMail subject]]];
	[mailEditController.subjectTextField becomeFirstResponder];
	[mailNavigationController pushViewController:mailEditController  animated:YES ];
	[pool release];
	
}

- (void)forwardAction:(id)sender
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	if([self isDataSourceAvailable]){
		NSString* url=	[NSString stringWithFormat:@"%@/%@/%@/($Drafts)/$new/?EditDocument&Form=m_MailReplyEdit&PresetFields=ParentUNID;%@",_serverName, _mailServer,_databaseName,[currentMail UNID]];
		NSURL* fetchReplyURL = [NSURL URLWithString:url];
		NSString* all=[self sendHttpRequest:fetchReplyURL isPost:NO postData:nil];
		NSRange range=[all rangeOfString:@"<textarea class=\"memoComposeField memoFieldText\" id=\"msgBody\" name=\"Body\">"];
		if(range.location!=NSNotFound){
			all=[all substringFromIndex:range.location+77];
			NSMutableString* modify=[[NSMutableString alloc] initWithString:[all substringToIndex:[all rangeOfString:@"</textarea>"].location]];
			[modify replaceOccurrencesOfString:@"=" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [modify length])];
			[mailEditController.textView setText: modify];
			[modify release];
		}
	}else{
		[mailEditController.textView setText: [currentMail content]];
	}

	[mailEditController.subjectTextField setText:[NSString stringWithFormat:@"Fwd:%@", [currentMail subject]]];
	[mailEditController.toTextField becomeFirstResponder];
	[mailNavigationController pushViewController:mailEditController  animated:YES ];
	[pool release];
}

- (void)refreshAction:(id)sender
{
	if(![self isDataSourceAvailable]){
		[self showNotLoginAlert];
		return;
	}
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	if(currentNavigationController==calendarNavigationController){
		[NSThread detachNewThreadSelector:@selector(getCalendarList) toTarget:self withObject:nil];
	}
	else if(currentNavigationController==mailNavigationController){
		[mailListViewController setMailStatusBarWithMessage:NSLocalizedString(@"UpdateMail", @"Updating mails...") animateIndicator:YES];
		[mailBoxDict removeAllObjects];
		[NSThread detachNewThreadSelector:@selector(getMailList) toTarget:self withObject:nil];
	}
	[pool release];
}



- (void)localAction:(id)sender
{
	if(_isOffline==NO){
		_isOffline=YES;
		//UI Alert window, this will cancel all the process
		//cancel all the process
		UIBarButtonItem *localItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Offline", @"")
																	  style: UIBarButtonItemStylePlain target:self action:@selector(localAction:)];
		self.mailBoxViewController.navigationItem.leftBarButtonItem=localItem;
		[localItem release];
		[transactionViewController addToHistroyTransaction:NSLocalizedString(@"OfflineMode", @"Switch to Offline mode")];
	}else{
		_isOffline=NO;
		UIBarButtonItem *remoteItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Online", @"")
																	   style:UIBarButtonItemStylePlain target:self action:@selector(localAction:)];
		self.mailBoxViewController.navigationItem.leftBarButtonItem=remoteItem;
		[remoteItem release];
		[mailBoxDict removeAllObjects];
		if(_sessionCookie==nil || [_sessionCookie isEqualToString:@""])
			[NSThread detachNewThreadSelector:@selector(login) toTarget:self withObject:nil];
		else
			[self getSavedTransaction];
		[transactionViewController addToHistroyTransaction:NSLocalizedString(@"OnlineMode", @"Switch to Online mode")];
	}
}

- (void)sendAction:(id)sender
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSURL* URL=[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/%@/($Drafts)/$new/?EditDocument&Form=m_MobileSend",_serverName, _mailServer,  _databaseName]];
	NSData* data = [[NSString stringWithFormat:@"Form=m_MailView&s_UsePlainText=1&MailOptions=1&h_SetPublishAction=h_Publish&h_SetSaveDoc=1&h_EditAction=h_Next&Form=Memo&s_NotesForm=Memo&SendTo=%@&CopyTo=%@&BlindCopyTo=%@&Subject=%@&Body=%@",
					 mailEditController.toTextField.text,mailEditController.ccTextField.text,mailEditController.bccTextField.text,mailEditController.subjectTextField.text,[[mailEditController.textView text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
					dataUsingEncoding: NSUTF8StringEncoding];//h_SetReturnURL=/mail/eye.nsf/iNotes/Mail/?OpenDocument&
	URLLoadingOperation* newOperation=[[URLLoadingOperation alloc] initWithType:2 URL:URL data:data description:
									   [NSString stringWithFormat:@"%@%@%@%@", NSLocalizedString(@"SendMailTransaction", ""),
										mailEditController.subjectTextField.text, NSLocalizedString(@"toString", ""),
										mailEditController.toTextField.text] fromDatabase:NO];
	[newOperation setQueuePriority:NSOperationQueuePriorityVeryHigh];
	[requestQueue addOperation:newOperation];
	[newOperation release];
	[currentNavigationController popViewControllerAnimated:YES];
	[mailEditController.textView setText: @""];
	[mailEditController.toTextField setText: @""];
	[mailEditController.ccTextField setText: @""];
	[mailEditController.bccTextField setText: @""];
	[mailEditController.subjectTextField setText: @""];
	[NSThread detachNewThreadSelector:@selector(refreshSent) toTarget:self withObject:nil];
	[pool release];
}

- (void)trashAction:(id)sender
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSURL* URL=[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/%@/iNotes/Proxy/?EditDocument",_serverName, _mailServer,  _databaseName]];
	NSData* trashData = [[NSString stringWithFormat:@"h_SetCommand=h_DeletePages&h_SetDeleteList=%@&h_EditAction=h_Next",[currentMail UNID]]
						 dataUsingEncoding: NSUTF8StringEncoding];
	URLLoadingOperation* newOperation=[[URLLoadingOperation alloc] initWithType:3 URL:URL data:trashData description:
									      [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"DeleteMailTransaction", ""), currentMail.subject] fromDatabase:NO];
	[newOperation setQueuePriority:NSOperationQueuePriorityVeryHigh];
	[requestQueue addOperation:newOperation];
	[newOperation release];
	
	[localMailDict removeObjectForKey:[currentMail UNID]];
	NSMutableArray* lastArray=[[NSMutableArray alloc] initWithArray:mailListViewController.currentMailList];
	
	int pos=[lastArray indexOfObject:currentMail];
	if((pos+1)==[lastArray count]){
		if(pos==0){
			[NSThread detachNewThreadSelector:@selector(getMailList) toTarget:self withObject:nil];
			[lastArray release];
			return;
		}
		else
			pos=0;
	}

	[lastArray removeObject:currentMail];
	[mailListViewController setDisplayList:lastArray];
	currentMail=[lastArray objectAtIndex:pos];
	[self showMailInfo:currentMail];
	//[NSThread detachNewThreadSelector:@selector(getMailList) toTarget:self withObject:nil];
	[lastArray release];
	[pool release];
	
}


#pragma mark preferenceAndSaving
- (void)loadPreference
{
	NSString *testValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"userNameKey"];
	if (testValue == nil)
	{
		// no default values have been set, create them here based on what's in our Settings bundle info
		NSString *pathStr = [[NSBundle mainBundle] bundlePath];
		NSString *settingsBundlePath = [pathStr stringByAppendingPathComponent:@"Settings.bundle"];
		NSString *finalPath = [settingsBundlePath stringByAppendingPathComponent:@"Root.plist"];
		
		NSDictionary *settingsDict = [NSDictionary dictionaryWithContentsOfFile:finalPath];
		NSArray *prefSpecifierArray = [settingsDict objectForKey:@"PreferenceSpecifiers"];
		
		NSString *userNameDefault=nil;
		NSString *passwordDefault=nil;
		NSString *mailPathDefault=nil;
		NSString *maxMailCountDefault=nil;
		NSString *databaseDefault=nil;
		NSString *serverDefault=nil;
		NSDictionary *prefItem=nil;
		NSString* previousDaysDefault=nil;
		NSString* futureDaysDefault=nil;
		NSString* toggleLoginDefault=nil;
		for (prefItem in prefSpecifierArray)
		{
			NSString *keyValueStr = [prefItem objectForKey:@"Key"];
			id defaultValue = [prefItem objectForKey:@"DefaultValue"];
			
			if ([keyValueStr isEqualToString:@"userNameKey"])
			{
				userNameDefault = defaultValue;
			}
			else if ([keyValueStr isEqualToString:@"passwordKey"])
			{
				passwordDefault = defaultValue;
			}
			else if ([keyValueStr isEqualToString:@"mailPathKey"])
			{
				mailPathDefault=defaultValue;
			}
			else if ([keyValueStr isEqualToString:@"databaseKey"])
			{
				databaseDefault=defaultValue;
			}
			else if ([keyValueStr isEqualToString:@"serverKey"])
			{
				serverDefault=defaultValue;
			}
			else if([keyValueStr isEqualToString:@"mailCountKey"])
			{
				maxMailCountDefault=defaultValue;
			}
			else if([keyValueStr isEqualToString:@"previousDaysKey"])
			{
				previousDaysDefault=defaultValue;
			}
			else if([keyValueStr isEqualToString:@"futureDaysKey"])
			{
				futureDaysDefault=defaultValue;
			}
			else if([keyValueStr isEqualToString:@"webSealKey"])
			{
				toggleLoginDefault=defaultValue;
			}
			
		}
		
		// since no default values have been set (i.e. no preferences file created), create it here
		NSDictionary *appDefaults =  [NSDictionary dictionaryWithObjectsAndKeys:
									  userNameDefault, @"userNameKey",
									  passwordDefault, @"passwordKey",
									  serverDefault, @"serverKey",
									  mailPathDefault, @"mailPathKey",
									  databaseDefault, @"databaseKey",
									  maxMailCountDefault, @"mailCountKey",
									  previousDaysDefault, @"previousDaysKey",
									  futureDaysDefault, @"futureDaysKey",
									  toggleLoginDefault, @"webSealKey",
									  nil];
		
		[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
		[[NSUserDefaults standardUserDefaults] synchronize];
	}
	
	// we're ready to do, so lastly set the key preference values
	_loginUsername=[[NSUserDefaults standardUserDefaults] stringForKey:@"userNameKey"];
	_loginPassword=[[NSUserDefaults standardUserDefaults] stringForKey:@"passwordKey"];
	_serverName=[[NSUserDefaults standardUserDefaults] stringForKey:@"serverKey"];
	_mailServer=[[NSUserDefaults standardUserDefaults] stringForKey:@"mailPathKey"];
	_databaseName=[[NSUserDefaults standardUserDefaults] stringForKey:@"databaseKey"];
	if((_databaseName==nil) || ([_databaseName isEqualToString:@"same as username"]))
		_databaseName=[[NSString stringWithFormat:@"%@.nsf", _loginUsername] retain];
	_defaultMaxMail=[[[NSUserDefaults standardUserDefaults] stringForKey:@"mailCountKey"] intValue];
	_useWebSeal=[[NSUserDefaults standardUserDefaults] boolForKey:@"webSealKey"];
	calendarListViewController.calendarEndDate=[[[NSUserDefaults standardUserDefaults] stringForKey:@"futureDaysKey"] intValue];
	calendarListViewController.calendarStartDate=-[[[NSUserDefaults standardUserDefaults] stringForKey:@"previousDaysKey"] intValue];
	
	if(_useWebSeal){
		testValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"serverGetCookieURLKey"];
		if (testValue == nil)
		{
			// no default values have been set, create them here based on what's in our Settings bundle info
			NSString *pathStr = [[NSBundle mainBundle] bundlePath];
			NSString *settingsBundlePath = [pathStr stringByAppendingPathComponent:@"Settings.bundle"];
			NSString *finalPath = [settingsBundlePath stringByAppendingPathComponent:@"WebSeal.plist"];
		
			NSDictionary *settingsDict = [NSDictionary dictionaryWithContentsOfFile:finalPath];
			NSArray *prefSpecifierArray = [settingsDict objectForKey:@"PreferenceSpecifiers"];
		
		
			NSString *getCookieURLDefault=nil;
			NSString *loginURLDefault=nil;
			NSDictionary *prefItem;
			for (prefItem in prefSpecifierArray)
			{
				NSString *keyValueStr = [prefItem objectForKey:@"Key"];
				id defaultValue = [prefItem objectForKey:@"DefaultValue"];
			
				if([keyValueStr isEqualToString:@"serverGetCookieURLKey"])
				{
					getCookieURLDefault=defaultValue;
				}
				else if([keyValueStr isEqualToString:@"serverLoginURLKey"])
				{
					loginURLDefault=defaultValue;
				}
			}
		
			// since no default values have been set (i.e. no preferences file created), create it here
			NSDictionary *appDefaults =  [NSDictionary dictionaryWithObjectsAndKeys:
									  getCookieURLDefault, @"serverGetCookieURLKey",
									  loginURLDefault, @"serverLoginURLKey",
									  nil];
		
			[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
			[[NSUserDefaults standardUserDefaults] synchronize];
		}
	
		// we're ready to do, so lastly set the key preference values

		_serverLoginURL=[[NSURL alloc] initWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"serverLoginURLKey"] ];
		_serverGetCookieURL=[[NSURL alloc] initWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"serverGetCookieURLKey"]] ;
	}

}

- (BOOL) writeApplicationData:(NSData *)data toFile:(NSString *)fileName {
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	if(!documentsDirectory) {
		NSLog (@"Documents directory not found!");
		return NO;
	}
	NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
	return ([data writeToFile:appFile atomically:YES]);
}

- (NSData *)applicationDataFromFile:(NSString *)fileName {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *appFile = [documentsDirectory stringByAppendingFormat:fileName];
	NSData *myData = [[NSData alloc] initWithContentsOfFile:appFile]  ;
	[pool release];
	return [myData autorelease];
}


#pragma mark databaseAction

//directory/dcmobi.nsf/6aa453f23e46ff8e85256590004feb16/4646464646464646000000004301001a?OpenDocument

- (void)getDirectoryInfoByPerson:(Person*)personInfo{
	if(![self isDataSourceAvailable])
	{
		[self showNotLoginAlert];
		return;
	}
	NSString* contentURL=[NSString stringWithFormat:@"%@/%@/directory/dcmobi.nsf/6aa453f23e46ff8e85256590004feb16/%@?OpenDocument",_serverName, _mailServer, [personInfo UNID]];
	NSURL* fetchContactContentUrl = [NSURL URLWithString:contentURL];
	NSString*all=[self sendHttpRequest:fetchContactContentUrl  isPost:NO  postData:nil];
	NSRange range=[all rangeOfString:@">Business:<"];
	NSRange range1;
	if(range.location!=NSNotFound){
		all=[all substringFromIndex:range.location+range.length];
		range=[all rangeOfString:@"<font size=\"2\">"];
		if(range.location !=NSNotFound){
			all=[all substringFromIndex:range.location+range.length];
			range1=[all rangeOfString:@"</font></td></tr>"];
			if(range1.location!=NSNotFound)
				[personInfo setEmail:[all substringToIndex:range1.location]];
		}
	}	
	range=[all rangeOfString:@">Business:<"];
	if(range.location!=NSNotFound){
		all=[all substringFromIndex:range.location];
		range=[all rangeOfString:@"<font size=\"2\">"];
		if(range.location !=NSNotFound){
			all=[all substringFromIndex:range.location+range.length];
			range1=[all rangeOfString:@"</font></td></tr>"];
			if(range1.location!=NSNotFound)
				[personInfo setWorkPhone:[all substringToIndex:range1.location]];
		}
	}
	[databaseInteraction updateDirectoryUseUNID:[personInfo UNID] withEmail:[personInfo email] phone:[personInfo workPhone]];
}

- (void)getPersonInfoByPerson:(Person*)personInfo{
	if(![self isDataSourceAvailable]){
		[self showNotLoginAlert];
		return;
	}
	NSString* contentURL=[NSString stringWithFormat:@"%@/%@/%@/(iNotes_Contacts)/%@/?EditDocument&Form=m_ContactEdit",_serverName, _mailServer,_databaseName, 	[personInfo UNID]];
	NSURL* fetchContactContentUrl = [NSURL URLWithString:contentURL];
	NSString*a=[self sendHttpRequest:fetchContactContentUrl  isPost:NO  postData:nil];
	NSData* urlData=[a dataUsingEncoding:NSUTF8StringEncoding];
	PersonInfoHTMLReader *streamingParser = [[PersonInfoHTMLReader alloc] initWithPerson:personInfo];
	NSError *parseError = nil;
	[streamingParser parseXMLFileFromData:urlData parseError:&parseError];
	[streamingParser release]; 
	[databaseInteraction updatePersonalWithPerson:personInfo];
}


#pragma mark processHTTP
static NSString* fileSplitSymbol=@" #_____# ";// use this symbol to split different attributes, for example, "sender #___# size"
-(void) savePreloadingMails:(NSArray*)mailArray mailBox:(NSString*)mailBox
{
	if(mailArray==nil)
		return;
	[mailListViewController setMailStatusBarWithMessage:[mailBoxDict objectForKey:[NSString stringWithFormat:@"%@updateTime",currentMailBox]] animateIndicator:NO];
	NSMutableString* allMail=[[NSMutableString alloc] init];
	int saveNumber=[mailArray count];
	if(saveNumber>25)
		saveNumber=25;
	for(int i=0;i<saveNumber;i++){
		Mail*eachMail = [mailArray objectAtIndex:i];
		[allMail appendFormat:@"%@%@", [eachMail attributes], fileSplitSymbol];
	}
	[self writeApplicationData:[allMail dataUsingEncoding:NSUTF8StringEncoding] toFile:[NSString stringWithFormat:@"MailContent%@",mailBox]];
	[allMail release];	
	[transactionViewController addToHistroyTransaction:[NSString stringWithFormat:@"%@%@", mailBox, NSLocalizedString(@"Saved", @" saved")]];
}

-(NSString *)sendHttpRequest:(NSURL*)url isPost:(BOOL)isPostMethod postData:(NSData*)data;
{	
	if(![self isDataSourceAvailable])
		return nil;
	[theLock lock];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;	
	CFStringRef method;
	if(isPostMethod)
		method=CFSTR("POST");
	else
		method=CFSTR("GET");
	CFHTTPMessageRef requestMsg = CFHTTPMessageCreateRequest(kCFAllocatorDefault, method, (CFURLRef) url, kCFHTTPVersion1_1);
	if(isPostMethod)
		CFHTTPMessageSetBody(requestMsg, (CFDataRef)data);
	
	CFHTTPMessageSetHeaderFieldValue(requestMsg, CFSTR("Cookie"), (CFStringRef)_sessionCookie);
	CFReadStreamRef readStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, requestMsg);
	CFReadStreamSetProperty(readStream, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue);
	CFReadStreamSetProperty(readStream, kCFStreamPropertyHTTPAttemptPersistentConnection,  kCFBooleanTrue);
	CFRelease(requestMsg);
	if (!readStream) {
		CFRelease(readStream);
		readStream=NULL;
		NSLog(@"sendHttpRequestAction: Stream Error");
		return nil;
	}

	if (!CFReadStreamOpen(readStream)) {
		CFRelease(readStream);
		readStream = NULL;
		NSLog(@"sendHttpRequestAction: Stream Open Error");
		return nil;
	}
	NSMutableString* responseString=[[NSMutableString alloc] init];
	BOOL done = FALSE;
	while (!done) {
		if (CFReadStreamHasBytesAvailable(readStream)) {
			UInt8 buffer[32768];
			CFIndex bytesRead = CFReadStreamRead(readStream, buffer, sizeof(buffer));
			NSString* get=[[NSString alloc] initWithBytes:(char*)buffer length:bytesRead encoding:NSUTF8StringEncoding];
			if(get!=nil)
				[responseString appendString:get];
			[get release];
		}
		else if(CFReadStreamGetStatus(readStream) == kCFStreamStatusAtEnd)
		{
			done = TRUE;
		}
	}
	CFReadStreamClose(readStream);
	
	CFRelease(readStream);
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	[theLock unlock];
	return [responseString autorelease];
}

//all Utilities

- (void)refreshSent
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[mailBoxDict removeObjectForKey:@"Sent"];
	[mailBoxDict removeObjectForKey:@"SentupdateTime"];
	[mailBoxDict removeObjectForKey:@"SentmailCount"];
	if(([currentMailBox isEqualToString:@"Sent"]) ){
		if([mailNavigationController topViewController]==mailContentController)
			[mailNavigationController popViewControllerAnimated:YES];
		[mailListViewController setMailStatusBarWithMessage:NSLocalizedString(@"UpdateMail", @"Updating mail...") animateIndicator:YES];
		[NSThread detachNewThreadSelector:@selector(getMailList) toTarget:self withObject:nil];
	}
	[pool release];
}



- (void)initUI
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	segmentedControl = [[[UISegmentedControl alloc] initWithItems:
						 [NSArray arrayWithObjects:
						  [UIImage imageNamed:@"SegmentUp.png"],
						  [UIImage imageNamed:@"SegmentDown.png"],
						  nil]] autorelease];
	[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
	segmentedControl.frame = CGRectMake(0, 0, 100, 30);
	segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
	segmentedControl.momentary = YES;	
	UIBarButtonItem *segmentBarItem = [[[UIBarButtonItem alloc] initWithCustomView:segmentedControl] autorelease];
	mailContentController.navigationItem.rightBarButtonItem = segmentBarItem;
	calendarContentController.navigationItem.rightBarButtonItem = segmentBarItem;
	
	UIBarButtonItem *openSafariItem = [[UIBarButtonItem alloc] initWithTitle:	@"Safari" style:UIBarButtonItemStylePlain
																	  target:self action:@selector(openInSafariAction:)];	
	mailWebView=[[UIWebView alloc] init];
	[mailWebView sizeToFit];
	mailWebView.scalesPageToFit=YES;
	mailWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
	mailWebView.delegate=self;
	mailWebViewController.view=mailWebView;
	mailWebViewController.navigationItem.rightBarButtonItem=openSafariItem;


	[openSafariItem release];
	
	calendarWebView=[[UIWebView alloc] init];
	[calendarWebView sizeToFit];
	calendarWebView.scalesPageToFit=YES;
	calendarWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
	calendarWebView.delegate=self;
	calendarContentController.view=calendarWebView;

	UIBarButtonItem *openINotesItem = [[UIBarButtonItem alloc] initWithTitle:	@"INotes" style:UIBarButtonItemStylePlain
									target:self action:@selector(openInINotesAction:)];
	contactContentController.navigationItem.rightBarButtonItem=openINotesItem;
	[openINotesItem release];
	contactContentWebView=[[UIWebView alloc] init];
	[contactContentWebView sizeToFit];
	contactContentWebView.scalesPageToFit=YES;
	contactContentWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
	contactContentWebView.delegate=self;
	contactContentWebViewController.view=contactContentWebView;
	
	
		
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString* path =[documentsDirectory stringByAppendingPathComponent:@"Attachments"] ;
	if (![fileManager fileExistsAtPath:path]) {
		[fileManager createDirectoryAtPath:path attributes:nil];
	}else{
		NSString *file;
		NSDirectoryEnumerator *dirEnum =[fileManager enumeratorAtPath:path];
		NSDictionary *fileAttributes;
		NSDate *fileModDate;
		NSError* error;
		NSString* filePath;
		while (file = [dirEnum nextObject]) {
			filePath=[path stringByAppendingPathComponent:file];
			fileAttributes = [fileManager fileAttributesAtPath:filePath traverseLink:YES];
			if (fileModDate = [fileAttributes objectForKey:NSFileModificationDate]) {	
				int timeInterval=[fileModDate timeIntervalSinceNow];
				if(timeInterval<-60*60*30){
					[fileManager removeItemAtPath:filePath error:&error];
				}
			}
		}
	}
	

	[pool release];
}

- (int)defaultMaxMailCount{
	return _defaultMaxMail;
}

- (void)configSegment:(int) SegmentIndex{
	if(SegmentIndex==0){
		[segmentedControl setEnabled:NO forSegmentAtIndex:0];
	}
	else if(SegmentIndex==1){
		[segmentedControl setEnabled:NO forSegmentAtIndex:1];
	}
	else{
		[segmentedControl setEnabled:YES forSegmentAtIndex:0];	
		[segmentedControl setEnabled:YES forSegmentAtIndex:1];	
	}		
}

- (void)readMoreMails
{	
	[mailBoxDict removeObjectForKey:currentMailBox];
	[mailBoxDict removeObjectForKey:[NSString stringWithFormat:@"%@updateTime", currentMailBox]];
	[mailBoxDict removeObjectForKey:[NSString stringWithFormat:@"%@mailCount", currentMailBox]];
	[mailListViewController setMailStatusBarWithMessage: NSLocalizedString(@"UpdateMail", @"") animateIndicator:YES];
	_defaultMaxMail=_defaultMaxMail*2;
	[NSThread detachNewThreadSelector:@selector(getMailList) toTarget:self withObject:nil];
}


- (void)loadLocalMails:(NSString*) mailBox {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSString* allMail=[[NSString alloc] initWithData:[self applicationDataFromFile:[NSString stringWithFormat:@"/MailContent%@",mailBox ]] encoding:NSUTF8StringEncoding];
	NSMutableArray* array=[[NSMutableArray alloc] initWithArray:[allMail componentsSeparatedByString:fileSplitSymbol]];
	[array removeLastObject];
	NSMutableArray* mails=[[NSMutableArray alloc] init];
	for (NSString* eachMail in array){
		Mail* mail=[[Mail alloc] initWithAttributes:eachMail];
		[mails addObject:mail];
		[localMailDict	setObject:mail forKey:[mail UNID]];
		[mail release];
	}
	[mailListViewController setDisplayList:mails];
	[allMail release];
	[array release];
	[mails release];
	[pool release];
	
}


- (BOOL)isDataSourceAvailable
{
	BOOL _isDataSourceAvailable;
	if(_isOffline || _sessionCookie==nil || [_sessionCookie isEqualToString:@""])
	{
		_isDataSourceAvailable=NO;
	}
	else{
		Boolean success;    
		const char* host_name="www.google.com";
        SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host_name);
        SCNetworkReachabilityFlags flags;
        success = SCNetworkReachabilityGetFlags(reachability, &flags);
        _isDataSourceAvailable = success && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
        CFRelease(reachability);
	}
	if(!_isDataSourceAvailable && [[requestQueue operations] count]!=0){
		[requestQueue cancelAllOperations];
	}	
	return _isDataSourceAvailable;
}




- (void)selectEmailFromDatabase
{
	ContactSelectionViewController* contactSelectionController= [[ContactSelectionViewController alloc] init];
	[currentNavigationController pushViewController:contactSelectionController  animated:YES];
	UIBarButtonItem* cancelItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Cancel", @"")	style:UIBarButtonItemStylePlain
	 target:self action:@selector(cancelEmailSelection:)];
	 contactSelectionController.navigationItem.rightBarButtonItem=	cancelItem;
	[cancelItem release];
	[contactSelectionController release];
}

- (void)cancelEmailSelection:(id)sender{
	[currentNavigationController popViewControllerAnimated:YES];
	[ContactSelectionViewController release];
}

-(void)returnSelectEmail:(NSString*)mail
{
	[currentNavigationController popViewControllerAnimated:YES];
	[mailEditController.toTextField setText:mail];
	[ContactSelectionViewController release];
}

-(int)totalMailCount{
	return [[mailBoxDict objectForKey:[NSString stringWithFormat:@"%@mailCount",currentMailBox]] intValue];
}

- (void)getSavedTransaction
{
	NSArray* array=[databaseInteraction getOperationsFromDatabase];
	for (URLLoadingOperation* operation in 	array){
		[operation setQueuePriority:NSOperationQueuePriorityVeryHigh];
		[requestQueue addOperation:operation];

	}
}

- (void)sendMailTo:(NSString*) receiver{
	[contactNavigationController pushViewController:mailEditController  animated:NO ];//presentModalViewController: mailEditController animated:YES];
	[mailEditController.toTextField setText:receiver];
	[mailEditController.toTextField becomeFirstResponder];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;	
}

-(void)showNotLoginAlert
{
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"NeedLogin", @"This function need login") message:@""
												   delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"OK") otherButtonTitles: nil];
	[alert show];	
	[alert release];
}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
}



- (void)setMailReadStatusWithUNID:(NSString *)mailUNID markRead:(BOOL)status 
{
	NSString* markRead;
	if(status==YES){
		markRead=@"h_ShimmerMarkRead";
	}
	else{
		markRead=@"h_ShimmerMarkUnRead";
	}
	NSString* url=	[NSString stringWithFormat:@"%@/%@/%@/iNotes/Proxy/?EditDocument",_serverName, _mailServer,_databaseName];
	NSURL* readURL = [NSURL URLWithString:url];
	NSData* data = [[NSString stringWithFormat:@"h_SetCommand=%@&h_SetDeleteList=%@&h_EditAction=h_Next",markRead, mailUNID]
						 dataUsingEncoding: NSUTF8StringEncoding];
	URLLoadingOperation* newOperation=[[URLLoadingOperation alloc] initWithType:6 URL:readURL data:data description:
										   @"" fromDatabase:NO];
	[newOperation setQueuePriority:NSOperationQueuePriorityVeryHigh];
	[requestQueue addOperation:newOperation];
	[newOperation release];

}


- (void)applicationWillTerminate:(UIApplication *)application
{
	[self savePreloadingMails:[mailBoxDict objectForKey:NSLocalizedString(@"Inbox", @"Inbox title")] mailBox:NSLocalizedString(@"Inbox", @"Inbox title")];
	[self savePreloadingMails:[mailBoxDict objectForKey:NSLocalizedString(@"Drafts", @"Drafts title")] mailBox:NSLocalizedString(@"Drafts", @"Drafts title")];
	[self savePreloadingMails:[mailBoxDict objectForKey:NSLocalizedString(@"Sent", @"Sent title")] mailBox:NSLocalizedString(@"Sent", @"Sent title")];
	[self savePreloadingMails:[mailBoxDict objectForKey:NSLocalizedString(@"All", @"All title")] mailBox:NSLocalizedString(@"All", @"All title")];
}
@end




/*-------Get Invitation Action, not work-------------
 NSURL* URL=[NSURL URLWithString:[NSString stringWithFormat:@"rbapns01/mail/eye.nsf/($Inbox)/1D0727E1956C5058CA25756800088C4A/?EditDocument&Form=h_PageUI"]];
 NSData* loginData1 = [[NSString stringWithFormat:@"h_SetEditCurrentScene=s_StdPageRead&h_EditAction=h_Next&s_ScanViewName=($Inbox)&h_SetCommand=h_ShimmerSave&h_SetSaveDoc=1&s_ScanFromClient=1&s_ScanUnid=1D0727E1956C5058CA25756800088C4A&h_MeetingCommand=8&SMessage=Accepted:"]
 dataUsingEncoding: NSUTF8StringEncoding];   //
 
 NSString* h=@"h_SetEditCurrentScene=s_StdPageRead&h_EditAction=h_Next&s_ScanViewName=($Inbox)&h_SetCommand=h_ShimmerSave&h_SetSaveDoc=1&s_ScanFromClient=1&s_ScanUnid=1D0727E1956C5058CA25756800088C4A&h_MeetingCommand=8&SMessage=Accepted:&StartTimeZone=Z=-10$DO=1$DL=10 1 1 4 1 1$ZN=AUS Eastern&EndTimeZone=Z=-10$DO=1$DL=10 1 1 4 1 1$ZN=AUS Eastern&LocalTimeZone=Z=-10$DO=1$DL=10 1 1 4 1 1$ZN=AUS Eastern&ThisInstDate=20090228T125900$Z=-10$DO=1$DL=10 1 1 4 1 1$ZN=AUS Eastern";
 h=[h stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 NSData* loginData2=[h dataUsingEncoding:NSUTF8StringEncoding];
 NSString* a=[self sendHttpRequest:URL isPost:YES postData:loginData1];
 NSLog(a);
 */


/*---if needed to save default view-------
//[[self mailNavigationController] pushViewController:mailListViewController animated:YES];
//	NSIndexPath* defaultIndex=[NSIndexPath indexPathForRow:0 inSection:0];
//	[self.mailBoxViewController tableView:[self.mailBoxViewController tableView] didSelectRowAtIndexPath:defaultIndex];
 */


/*----------Create clendar action, not work-----------
	
 NSURL* getCalendarURL=[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/%@/($Calendar)/$new/?EditDocument&Form=h_PageUI&PresetFields=h_EditAction;h_New,s_NotesForm;Appointment,ThisStartDate;20090817T050000Z,s_ViewName;($Calendar)",_serverName, _mailServer,  _databaseName]];
 NSString* responseString2=[self sendHttpRequest:getCalendarURL	isPost:NO postData:nil];//
 NSURL* saveCalendarURL=[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/%@/($Calendar)/$new/?EditDocument&Form=h_PageUI&ui=inotes&PresetFields=s_NotesForm;Appointment",_serverName, _mailServer,  _databaseName]];
 NSString* string1 = [NSString stringWithFormat:@"%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&%@&From=%@&Principal=%@",
 @"h_EditAction=h_Next",
 @"h_SetEditCurrentScene=s_StdPageEdit",
 @"h_SetEditNextScene=s_StdPageNewRedirect",
 @"h_NoSceneTrail=1",
 @"h_SetCommand=h_ShimmerSave",
 @"h_SetSaveDoc=1",
 @"h_Name=s1",
 @"h_SetPublishAction=h_Publish",
 [@"s_ViewName=($Calendar)" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
 @"s_DisclaimerIsAdded=0",
 [@"s_ScanViewName=($Calendar)" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
 @"s_ScanUnid=NEW",
 @"h_RichTextItem=Body",
 @"h_NumOfPageText=1",
 @"s_UsePlainTextAndHTML=0",
 @"body=detail1",
 @"RequestResponse=on",
 @"Categories=Vacation",
 @"Subject=subject1",
 @"Location=location1",
 @"DocCtxCbxdispMeetingTypeArea=1",
 @"FontNames=0",
 @"FontSize=2",
 @"Form=Appointment",
 @"AppointmentType=0",
 @"OnlineMeeting=0",
 @"$KeepPrivate=0",
 @"s_IsPublished=0",
 
 [@"h_SceneContext=putAway['publishAction']&&&&&&putAway['publishFolderTitle']&&&&&&putAway['ME']&&&&&&putAway['publishFolderPageUnid']&&&&&&putAway['tocPosition']&&&&&&putAway['tmpText']&&&&&&putAway['selectedFolderIndex']&&&0&&&putAway['BSi']&&&&&&" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
 [@"IntDate	Tue 08/18/2009" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], 
 [@"IntTime=04:00PM"  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], 
 [@"IntZoneAreaCtl=AUS Eastern"  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
 [@"IntDur=01h 00m"  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
 [@"IntEndDate=Tue 08/18/2009"  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], 	
 [@"IntEndTime=05:00PM"  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
 [@"IntEndZoneAreaCtl=AUS Eastern"  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
 [@"HaikuUploadAttachment0=filename="" Content-Type: application/octet-stream" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
 [@"StartDate=20090818T160000$Z=-10$DO=1$DL=10 1 1 4 1 1$ZN=AUS Eastern"  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], 
 [@"EndDate=20090818T170000$Z=-10$DO=1$DL=10 1 1 4 1 1$ZN=AUS Eastern"  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], 
 [@"StartTimeZone=Z=-10$DO=1$DL=10 1 1 4 1 1$ZN=AUS Eastern"  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], 
 [@"EndTimeZone=Z=-10$DO=1$DL=10 1 1 4 1 1$ZN=AUS Eastern"  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], 
 [@"LocalTimeZone=Z=-10$DO=1$DL=10 1 1 4 1 1$ZN=AUS Eastern" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
 [@"$Alarm=0" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], 	 
 [@"$PublicAccess=1" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], 
 [@"$BusyPriority=1" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
 [@"ThisStartDate=20090818T160000$Z=-10$DO=1$DL=10 1 1 4 1 1$ZN=AUS Eastern"  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
 [@"ThisEndDate=20090818T170000$Z=-10$DO=1$DL=10 1 1 4 1 1$ZN=AUS Eastern"  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
 [@"$PreventReplies=0" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], 
 
 [@"CN=Eric Ye/OU=Australia/O=RedBull"  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], 
 [@"CN=Eric Ye/OU=Australia/O=RedBull"  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ];
 NSData* data1=[string1 dataUsingEncoding:NSUTF8StringEncoding];
 NSString* responseString1=[self sendHttpRequest:saveCalendarURL isPost:YES postData:data1];	
 */

